/**
 * Copyright (c) 2015-2020, wss 王山山
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.wss.conversion.meta;

import java.util.Optional;
import java.util.function.Function;

import com.jfinal.plugin.activerecord.Model;
import com.wss.conversion.Constants;
import com.wss.conversion.annotations.Dao;
import com.wss.utils.ReflectionUtil;
import com.wss.utils.StringUtil;
import com.wss.utils.annotations.NotNull;

/**
 * 获取Model相关的信息，包括表名，主键名，是否自动注册等
 * 
 * @author wss
 *
 */
public final class ModelMeta {
	private Class<?> modelClass;
	private Dao dao;
	private boolean hasDao;
	
	public ModelMeta(@NotNull Class<?> modelClass) {
		this.modelClass = modelClass;
		Optional<Dao> daoOptional = ReflectionUtil.getAnnotationByType(modelClass, Constants.ModelConstants.DAO_CLASS);
		this.hasDao = daoOptional.isPresent();
		this.dao = this.hasDao ? daoOptional.get() : null;
	}
	
	public String getTable() {
		if (hasValue(e -> e.value())) {
			return dao.value();
		}
		String table = StringUtil.subtractSuffix(modelClass.getSimpleName(), Constants.ModelConstants.MODEL_SUFFIX);
		return StringUtil.firstLetterLowerCase(table);
	}
	
	public String getPk() {
		String pk = "id";
		if (hasValue(e -> e.pk())) {
			pk = dao.pk();
		}
		return pk;
	}
	
	private boolean hasValue(Function<Dao, String> function) {
		return hasDao && StringUtil.isNotBlank(function.apply(dao));
	}
	
	public boolean isScan() {
		return hasDao ? dao.isScan() : true;
	}
	
	@SuppressWarnings({ "unchecked" })
	public Class<? extends Model<?>> getModelClass() {
		return (Class<? extends Model<?>>) modelClass;
	}

	@Override
	public String toString() {
		return "Table: " + getTable() + ", PK: " + getPk() + ", isScan: " + isScan();
	}
}
